package org.example.device.control;

import org.example.device.protocol.DeviceProtocol;
import org.example.device.protocol.ProtocolResult;
import org.example.device.registry.DeviceProtocolRegistry;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

/**
 * 抽象设备控制器
 * 提供设备控制的通用实现
 */
public abstract class AbstractDeviceController implements DeviceControlInterface {
    
    @Autowired
    protected DeviceProtocolRegistry protocolRegistry;
    
    /**
     * 获取设备协议
     * 子类可以重写此方法来指定特定的协议
     */
    protected DeviceProtocol getDeviceProtocol() {
        // 默认使用HTTP协议，子类可以重写此方法
        return protocolRegistry.getProtocol("HTTP");
    }
    
    @Override
    public DeviceControlResult executeCommand(DeviceControlCommand command) {
        try {
            // 验证命令
            if (!validateCommand(command)) {
                return DeviceControlResult.failure("命令验证失败", "INVALID_COMMAND");
            }
            
            // 构建协议参数
            Map<String, Object> parameters = buildProtocolParameters(command);
            
            // 发送协议命令
            ProtocolResult protocolResult = getDeviceProtocol().sendCommand(
                command.getDeviceId(), 
                command.getCommandType(), 
                parameters
            );
            
            if (protocolResult.isSuccess()) {
                return DeviceControlResult.success("设备控制成功", protocolResult.getData());
            } else {
                return DeviceControlResult.failure("设备控制失败: " + protocolResult.getMessage(), 
                    protocolResult.getErrorCode());
            }
        } catch (Exception e) {
            return DeviceControlResult.failure("设备控制异常: " + e.getMessage(), "CONTROL_EXCEPTION");
        }
    }
    
    @Override
    public Map<String, Object> getDeviceStatus(Long deviceId) {
        try {
            ProtocolResult result = getDeviceProtocol().getDeviceStatus(deviceId);
            if (result.isSuccess()) {
                @SuppressWarnings("unchecked")
                Map<String, Object> data = (Map<String, Object>) result.getData();
                return data;
            } else {
                return Collections.singletonMap("error", result.getMessage());
            }
        } catch (Exception e) {
            return Collections.singletonMap("error", "获取设备状态异常: " + e.getMessage());
        }
    }
    
    @Override
    public boolean isDeviceOnline(Long deviceId) {
        try {
            ProtocolResult result = getDeviceProtocol().checkConnection(deviceId);
            return result.isSuccess();
        } catch (Exception e) {
            return false;
        }
    }
    
    @Override
    public DeviceControlResult testConnection(Long deviceId) {
        try {
            ProtocolResult result = getDeviceProtocol().checkConnection(deviceId);
            if (result.isSuccess()) {
                return DeviceControlResult.success("设备连接正常");
            } else {
                return DeviceControlResult.failure("设备连接异常: " + result.getMessage());
            }
        } catch (Exception e) {
            return DeviceControlResult.failure("设备连接测试异常: " + e.getMessage());
        }
    }
    
    /**
     * 验证控制命令
     */
    protected boolean validateCommand(DeviceControlCommand command) {
        if (command == null || command.getDeviceId() == null || command.getCommandType() == null) {
            return false;
        }
        
        List<String> supportedCommands = getSupportedCommands(command.getDeviceId());
        return supportedCommands.contains(command.getCommandType());
    }
    
    /**
     * 构建协议参数
     */
    protected Map<String, Object> buildProtocolParameters(DeviceControlCommand command) {
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("value", command.getValue());
        parameters.put("action", command.getAction());
        parameters.put("userId", command.getUserId());
        parameters.put("timestamp", command.getTimestamp());
        
        if (command.getParameters() != null) {
            parameters.putAll(command.getParameters());
        }
        
        return parameters;
    }
    
    /**
     * 获取设备属性 - 子类实现
     */
    @Override
    public abstract Map<String, Object> getDeviceProperties(Long deviceId);
    
    /**
     * 设置设备属性 - 子类实现
     */
    @Override
    public abstract DeviceControlResult setDeviceProperties(Long deviceId, Map<String, Object> properties);
    
    /**
     * 获取支持的指令类型 - 子类实现
     */
    @Override
    public abstract List<String> getSupportedCommands(Long deviceId);
    
    /**
     * 获取设备类型 - 子类实现
     */
    @Override
    public abstract String getDeviceType();
    
    /**
     * 获取协议类型
     */
    @Override
    public String getProtocolType() {
        return getDeviceProtocol().getProtocolType();
    }
}
